package com.yilin.platform.service.impl.truck;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.platform.base_core.application.PageData;
import com.yilin.platform.base_core.commons.utils.ParamUtil;
import com.yilin.platform.base_core.commons.utils.StringUtil;
import com.yilin.platform.base_core.tools.QueryUtil;
import com.yilin.platform.entity.enums.user.UserType;
import com.yilin.platform.entity.system.TruckEnergyType;
import com.yilin.platform.entity.system.TruckPlate;
import com.yilin.platform.entity.system.TruckType;
import com.yilin.platform.entity.truck.TransportLicense;
import com.yilin.platform.entity.truck.TravelLicense;
import com.yilin.platform.entity.truck.TruckVehicle;
import com.yilin.platform.entity.user.Account;
import com.yilin.platform.entity.user.Organize;
import com.yilin.platform.mapper.truck.TruckVehicleMapper;
import com.yilin.platform.service.impl.capital.AdvanceMoneyService;
import com.yilin.platform.service.impl.order.TransitOrdinaryService;
import com.yilin.platform.service.impl.system.ParamService;
import com.yilin.platform.service.impl.user.AccountService;
import com.yilin.platform.service.impl.user.OrganizeService;
import com.yilin.platform.service.truck.ITransportLicenseService;
import com.yilin.platform.service.truck.ITravelLicenseService;
import com.yilin.platform.service.truck.ITruckVehicleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;


/**
 * 车辆服务
 *
 * @author zhangjinyuan
 * @date 2022/10/24
 */
@Service
@Transactional
public class TruckVehicleService extends ServiceImpl<TruckVehicleMapper, TruckVehicle> implements ITruckVehicleService {

    @Resource
    ITravelLicenseService travelLicenseService;
    @Resource
    ITransportLicenseService transportLicenseService;

    @Resource
    TruckVehicleMapper truckVehicleMapper;

    @Resource
    AccountService accountService;
    @Resource
    OrganizeService organizeService;
    @Resource
    ParamService paramService;
    @Resource
    AdvanceMoneyService advanceMoneyService;
    @Resource
    TransitOrdinaryService transitOrdinaryService;

    /**
     * 车辆找查：根据驾驶员获取车辆
     */
    @Override
    public List<TruckVehicle> getVehicleListByDriverId(String driverId) {
        return truckVehicleMapper.getVehicleListByTruckUserId(driverId);
    }

    /**
     * 车辆找查：根据驾驶员获取车辆
     */
    @Override
    public TruckVehicle getVehicleById(String vehicleId) {
        return truckVehicleMapper.selectById(vehicleId);
    }


    /**
     * 车辆找查：车牌号查找
     */
    @Override
    public TruckVehicle getVehicleByNo(String trackNo) {
        return truckVehicleMapper.selectOne(new QueryWrapper<TruckVehicle>().eq("track_no", trackNo));
    }

    /**
     * /**
     * 车辆找查：获取组织全部车辆
     */
    @Override
    public List<TruckVehicle> getVehicleListByOrganizeId(String organizeId, TruckVehicle query) {
        List<TruckVehicle> vehicleList = truckVehicleMapper.getVehicleListByOrganizeId(organizeId, query);
//        return setEquipmentInfo(vehicleList);
        return vehicleList;
    }

    @Override
    public List<TruckVehicle> getUnUsedVehicleListByOrganizeId(String organizeId) {
        QueryWrapper<TruckVehicle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("truck_status", TruckVehicle.TruckStatus.unused);
        return truckVehicleMapper.selectList(queryWrapper);
    }

    @Override
    public Long getOrganzieByListCount(Organize organize) {
        QueryWrapper<TruckVehicle> queryWrapper = new QueryWrapper<>();
        if (organize.getUserType() != UserType.platformUser && organize.getUserType() != UserType.adminUser) {
            queryWrapper.and(wrapper ->
                    wrapper.eq("organize_id", organize.getId())
                            .or()
                            .eq("superior_plat_id", organize.getSuperiorPlatOrganizeId())
            );
        }
        return truckVehicleMapper.selectCount(queryWrapper);
    }


    /**
     * 获取车辆分页
     */
    @Override
    public PageData<TruckVehicle> getTruckVehiclePage(Account loginUser, TruckVehicle query, Integer page, Integer limit) {
        QueryWrapper<TruckVehicle> queryWrapper = new QueryWrapper<>();
        QueryUtil.buildOrganizeIdOrSuperiorPlatIdWrapper(queryWrapper, loginUser);
        QueryUtil.andQueryWrapper(queryWrapper, query);
        PageData<TruckVehicle> pageData = page(new PageData<>(page, limit), queryWrapper);
        List<TruckVehicle> vehicleList = new ArrayList<>();
        if (pageData.getList() != null && !pageData.getList().isEmpty()) {
            String[] ids = pageData.getList().stream().map(TruckVehicle::getId).toArray(String[]::new);
            List<Map<String, Object>> capitalMapList = advanceMoneyService.getAdvanceMoneyPage(ids);
            List<Map<String, Object>> orderMapList = transitOrdinaryService.getYearMonthDayMap(ids);
            pageData.getList().forEach(truckVehicle -> {
                String truckId = truckVehicle.getId(); // Assuming getId() returns Long
                AtomicReference<Map<String, Object>> resultMap = new AtomicReference<>();
                AtomicReference<Map<String, Object>> orderMap = new AtomicReference<>();
                for (Map<String, Object> stringObjectMap : capitalMapList) {
                    if (stringObjectMap != null && stringObjectMap.get("truckId").equals(truckId)) {
                        resultMap.set(stringObjectMap);
                    }
                }

                for (Map<String, Object> stringObjectMap : orderMapList) {
                    if (stringObjectMap != null && stringObjectMap.get("truckId").equals(truckId)) {
                        orderMap.set(stringObjectMap);
                    }
                }

                if (resultMap.get() != null && !resultMap.get().isEmpty()) {
                    truckVehicle.setCapitalMap(resultMap.get());
                }
                if (orderMap.get() != null && !orderMap.get().isEmpty()) {
                    truckVehicle.setOrderMap(orderMap.get());
                }
                vehicleList.add(truckVehicle);
            });
        }
        pageData.setList(vehicleList);
        return pageData;
    }


    //-----------------------------------------------保存区-------------------------------------------

    /**
     * 保存车辆
     */
    @Override
    public void saveTruckVehicle(Account loginUser, TruckVehicle truckVehicle, TravelLicense travelLicense, TransportLicense transportLicense) {
        Organize organize = organizeService.getOrganizeById(loginUser.getOrganizeId());
        TruckEnergyType energyType = paramService.getTruckEnergyById(truckVehicle.getTruckEnergyTypeId());
        TruckType truckType = paramService.getTruckTypeById(truckVehicle.getTruckTypeId());
        TruckPlate truckPlate = paramService.getTruckPlateById(truckVehicle.getCardPlateId());
        // #### 设置基本信息
        truckVehicle.setOrganizeId(organize.getId());
        truckVehicle.setOrganizeName(organize.getOrganizeName());
        truckVehicle.setSuperiorPlatId(organize.getSuperiorPlatOrganizeId());
        truckVehicle.setSuperiorPlatName(organize.getSuperiorPlatOrganizeName());
        truckVehicle.setOrganizeLogo(organize.getOrganizeLogo());
        truckVehicle.setManageUserId(loginUser.getId());
        truckVehicle.setManageUserName(loginUser.getName());
        truckVehicle.setManageUserAvatar(loginUser.getAvatar());
        truckVehicle.setManageUserPhone(loginUser.getPhone());
        truckVehicle.setTruckEnergyTypeName(energyType.getName());
        truckVehicle.setTruckEnergyTypeCode(energyType.getCode());
        truckVehicle.setTruckTypeName(truckType.getName());
        truckVehicle.setTruckTypeCode(truckType.getCode());
        truckVehicle.setCardPlateName(truckPlate.getName());
        truckVehicle.setCardPlateCode(truckPlate.getCode());
        truckVehicle.setVehicleWeight(travelLicense.getVehicleWeight());
        truckVehicle.setLoadingWeight(travelLicense.getLoadingWeight());
        truckVehicle.setTruckStatus(TruckVehicle.TruckStatus.auth);
        //赋值
        if (truckVehicle.getTruckStatus() == null) truckVehicle.setTruckStatus(TruckVehicle.TruckStatus.unused);
        // #### 检查车牌号
        TruckVehicle oldTruckVehicle = getOne(new QueryWrapper<TruckVehicle>().eq("track_no", truckVehicle.getTrackNo()));
        if (oldTruckVehicle != null && (truckVehicle.getId() == null || !oldTruckVehicle.getId().equals(truckVehicle.getId()))) {
            ParamUtil.notEquals("平台已存在该车牌号", oldTruckVehicle.getId(), truckVehicle.getId());
        }
        //#### 个人用户如果已完成证件认证并且没有绑定其他车辆，自动绑定
        truckVehicle.setTruckUserId(loginUser.getId());
        truckVehicle.setTruckUserAvatar(loginUser.getAvatar());
        truckVehicle.setTruckUserPhone(loginUser.getPhone());
        truckVehicle.setTruckUserName(loginUser.getName());
        if (StringUtil.isEmpty(truckVehicle.getId())) {
            truckVehicle.setCreateTime(new Date());
            truckVehicle.setAddUserId(loginUser.getId());
            save(truckVehicle);
        } else {
            truckVehicle.setUpdateTime(new Date());
            truckVehicle.setUpdateUserId(loginUser.getId());
            updateById(truckVehicle);
        }
        //保存行驶证
        travelLicense.setVehicleId(truckVehicle.getId());
        travelLicense.setTruckEnergyTypeName(energyType.getName());
        travelLicense.setTruckEnergyTypeCode(energyType.getCode());
        travelLicense.setTruckTypeName(truckType.getName());
        travelLicense.setTruckTypeCode(truckType.getCode());
        travelLicense.setVehicleLong(truckVehicle.getVehicleLong());
        travelLicense.setVehicleWidth(truckVehicle.getVehicleWidth());
        travelLicense.setVehicleHeight(truckVehicle.getVehicleWeight());
        travelLicense.setLoadingWeight(truckVehicle.getLoadingWeight());
        travelLicense.setLoadingWeight(truckVehicle.getLoadingWeight());
        travelLicense.setTruckNo(truckVehicle.getTrackNo());
        travelLicense.setTruckTypeId(truckVehicle.getTruckTypeId());
        travelLicense.setTruckTypeCode(truckVehicle.getTruckTypeCode());
        travelLicense.setTruckTypeName(truckVehicle.getTruckTypeName());
        travelLicense.setTruckEnergyTypeId(truckVehicle.getTruckEnergyTypeId());
        travelLicense.setTruckEnergyTypeCode(truckVehicle.getTruckEnergyTypeCode());
        travelLicense.setTruckEnergyTypeName(truckVehicle.getTruckEnergyTypeName());
        travelLicenseService.saveTravelLicense(loginUser, travelLicense);
        //保存道路运输证
        if (transportLicense != null) {
            ParamUtil.isNull(transportLicense, "道路运输证为空");
            transportLicense.setVehicleId(truckVehicle.getId());
            transportLicense.setVehicleNo(truckVehicle.getTrackNo());
            transportLicenseService.saveTransportLicense(loginUser, transportLicense);
        }
        //####绑定设备号


    }

    /**
     * 绑定驾驶员
     */
    @Override
    public void bindTruckUser(Account loginUser, Account truckUser, TruckVehicle truckVehicle, TruckVehicle originalTruckVehicle) {
        //解绑司机原有车辆
        if (originalTruckVehicle != null) {
            originalTruckVehicle.setTruckUserId("");
            originalTruckVehicle.setTruckUserAvatar("");
            originalTruckVehicle.setTruckUserPhone("");
            originalTruckVehicle.setTruckUserName("");
            originalTruckVehicle.setUpdateTime(new Date());
            originalTruckVehicle.setUpdateUserId(loginUser.getId());
            updateById(originalTruckVehicle);
        }
        truckVehicle.setTruckUserId(truckUser.getId());
        truckVehicle.setTruckUserAvatar(truckUser.getAvatar());
        truckVehicle.setTruckUserPhone(truckUser.getPhone());
        truckVehicle.setTruckUserName(truckUser.getName());
        truckVehicle.setUpdateTime(new Date());
        truckVehicle.setUpdateUserId(loginUser.getId());
        updateById(truckVehicle);
    }

    /**
     * 绑定驾驶员
     */
    @Override
    public void editBindVehicle(Organize organize,TruckVehicle truckVehicle) {
        truckVehicle.setOrganizeId(organize.getId());
        truckVehicle.setOrganizeName(organize.getOrganizeName());
        truckVehicle.setOrganizeLogo(organize.getOrganizeLogo());
        truckVehicle.setManageUserId(organize.getManagerUserId());
        truckVehicle.setManageUserName(organize.getManagerUserName());
        truckVehicle.setManageUserAvatar(organize.getManagerUserAvatar());
        truckVehicle.setManageUserPhone(organize.getManagerUserPhone());
        truckVehicle.setTruckUserId(organize.getManagerUserId());
        truckVehicle.setTruckUserName(organize.getManagerUserName());
        truckVehicle.setTruckUserPhone(organize.getManagerUserPhone());
        truckVehicle.setTruckUserAvatar(organize.getManagerUserAvatar());
        TravelLicense travelLicense=travelLicenseService.getTravelLicenseByTruckId(truckVehicle.getId());
        if(travelLicense!=null){
            travelLicense.setOrganizeId(organize.getId());
            truckVehicle.setOrganizeName(organize.getOrganizeName());
            truckVehicle.setSuperiorPlatId(organize.getSuperiorPlatOrganizeId());
            truckVehicle.setSuperiorPlatName(organize.getSuperiorPlatOrganizeName());
        }
        TransportLicense transportLicense = transportLicenseService.getTransportLicenseByTruckId(truckVehicle.getId());
        if(transportLicense != null) {
            transportLicense.setOrganizeId(organize.getId());
            transportLicense.setOrganizeName(organize.getOrganizeName());
            transportLicense.setSuperiorPlatId(organize.getSuperiorPlatOrganizeId());
            transportLicense.setSuperiorPlatName(organize.getSuperiorPlatOrganizeName());
        }
        updateById(truckVehicle);
    }


}
